import {Component, OnInit, Input} from '@angular/core';
import {ApiService} from "@core/services/http/api.service";
import {GridConfigService} from 'app/core/config/grid-config.service';
import {GridOptions} from '@ag-grid-community/core';
import {ApesMessageService} from "@shared/apes/message";
import {UserAuthService} from "@core/services/user-auth.service";
import { BiService } from '../../bi.service';

@Component({
  selector: 'apes-shop-traffic',
  templateUrl: './shop-traffic.component.html',
  styleUrls: ['../door-tube-center-all.scss']
})
export class ShopTrafficComponent implements OnInit {

  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  height: any = window.innerHeight - 480 + 'px';

  endDate = null;      // 默认结束时间
  startDate = null;    // 默认开始时间 当天的前7天

  endTime = null;      // 传的结束时间
  startTime = null;    // 传的起始时间

  // 饼图相关
  salesPieData: any;
  shoucidd = [];
  daodiancl = [];
  scdd: any;
  ddcl: any;

  vipPieData: any;
  feihys = [];
  danwhy = [];
  huiys = [];
  fhys: any;
  dwhy: any;
  hys: any;

  wechatPieData: any;
  weixgz = [];
  weigz = [];
  wxygz: any;
  wxwgz: any;

  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  companyData:any;
  companyList: any[];

  startValueChange = () => {
    if (this.startDate > this.endDate) {
      this.endDate = null;
    }
  };
  endValueChange = () => {
    if (this.startDate > this.endDate) {
      this.startDate = null;
    }
  };

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private msg: ApesMessageService,
              private userAuthService: UserAuthService,
              private bi: BiService) {
    this.columnDefs = [
      {headerName: "日期", field: 'XZRQ_SJ'},
      {headerName: "到店总数", field: 'ZDDS'},
      {headerName: "首次到店数", field: 'SCDDS'},
      {headerName: "会员数", field: 'HYS'},
      {headerName: "非会员数", field: 'FHYS'},
      {headerName: "单位车辆数", field: 'DWCLS'},
      {headerName: "微信关注比例", field: 'WXGZBL'},
      {headerName: "保险转化率", field: 'BXZHL'},
      {headerName: "年卡转化率", field: 'NKZHL'}
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 20,
      rowHeight: 35
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.companyList = [];
    this.companyList.push(this.companyId);
  }

  ngOnInit() {
    // 默认 请求 30天 数据
    this.endDate = new Date();
    this.startDate = new Date(this.endDate.getTime() - (7 * 24 * 60 * 60 * 1000));
    this.bi.getCompany(this.userInfo.userAccount.post.localPermit.id).then(value => { this.companyData = value });
    this.submit();
  }

  submit() {
    // if(this.companyList.length <= 0){
    //   this.companyList.push(this.companyId);
    // }
    this.rowData = [];
    this.shoucidd = [];
    this.daodiancl = [];
    this.scdd = 0;
    this.ddcl = 0;

    this.feihys = [];
    this.danwhy = [];
    this.huiys = [];
    this.fhys = 0;
    this.dwhy = 0;
    this.hys = 0;

    this.weixgz = [];
    this.weigz = [];
    this.wxygz = 0;
    this.wxwgz = 0;
    // 传的时间 进行转换
    this.startTime = (this.startDate.toISOString()).slice(0, 10);
    this.endTime = (this.endDate.toISOString()).slice(0, 10);

    this.getTablesData();
  }

  getTablesData() {
    let data = {
      'interfaceMethod': 'ipmMgzzForAppService.Ddzcl',
      'pdata': {'Start_XZRQ_SJ': this.startTime, 'End_XZRQ_SJ': this.endTime, 'companyId': this.companyList}
    };
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            data = data.sort(this.sortarr('XZRQ_SJ'));
            for (let i = 0, len = data.length; i < len; i++) {
              // 到店车流饼图相关
              this.shoucidd.push(data[i].SCDDS);
              this.daodiancl.push(data[i].ZDDS);
              // 会员饼图相关
              this.feihys.push(data[i].FHYS);
              this.danwhy.push(data[i].DWCLS);
              this.huiys.push(data[i].HYS);
              // 微信饼图相关
              this.weigz.push(data[i].WXWGZBL);
              this.weixgz.push(data[i].WXGZBL);
            }
            // 到店车流饼图
            for (let i = 0, len = this.shoucidd.length; i < len; i++) {
              this.scdd += this.shoucidd[i];
            }
            for (let i = 0, len = this.daodiancl.length; i < len; i++) {
              this.ddcl += this.daodiancl[i];
            }
            // 会员饼图
            for (let i = 0, len = this.feihys.length; i < len; i++) {
              this.fhys += this.feihys[i];
            }
            for (let i = 0, len = this.danwhy.length; i < len; i++) {
              this.dwhy += this.danwhy[i];
            }
            for (let i = 0, len = this.huiys.length; i < len; i++) {
              this.hys += this.huiys[i];
            }
            // 微信饼图
            for (let i = 0, len = this.weigz.length; i < len; i++) {
              this.wxwgz += this.weigz[i];
            }
            for (let i = 0, len = this.weixgz.length; i < len; i++) {
              this.wxygz += this.weixgz[i];
            }
            for (let i = 0, len = data.length; i < len; i++) {
              data[i]['NKZHL'] = data[i]['NKZHL'] + '%';
              data[i]['BXZHL'] = data[i]['BXZHL'] + '%';
              data[i]['WXGZBL'] = data[i]['WXGZBL'] + '%';
            }
            this.rowData = data;
            if( this.rowData.length === 0 ) {
              this.msg.info(`未找到满足条件的数据`);
            }
            // 加载 饼图
            this.salesPieData = this.getSalesTypePie();
            this.vipPieData = this.getVipTypePie();
            this.wechatPieData = this.getWechatPieData();
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 饼图
  getSalesTypePie() {
    return [
      {x: '首次到店', y: this.scdd},
      {x: '到店车辆', y: this.ddcl},
    ];
  }

  getVipTypePie() {
    return [
      {x: '非会员数', y: this.fhys},
      {x: '单位会员', y: this.dwhy},
      {x: '会员数', y: this.hys},
    ];
  }

  getWechatPieData() {
    return [
      { x: '未关注微信', y: this.wxwgz },
      { x: '已关注微信', y: this.wxygz },
    ];
  }

// 排序 倒序
  sortarr(key) {
    return function (a, b) {
      a[key] == undefined ? a[key] = 0 :
        b[key] == undefined ? b[key] = 0 : 0 ;
      return b[key] - a[key];
    };
  }

}
